<?php
namespace Wechat\Controller;

use Common\Controller\AdminController;
use Common\Model\KeywordModel;
use wechat\WeChat;

class ApiController extends AdminController {

    public function __init() {
        (new WeChat())->valid();
    }

    public function handler() {
        $keyword_model = new KeywordModel();

        //消息管理模块
        $instance = (new WeChat())->instance('message');
        //判断是否是文本消息
        if ($instance->isTextMsg()) {
            //获取消息内容
            $message = $instance->getMessage();
            //向用户回复消息
            $content = (string)$message->Content;
            if ($data = $keyword_model->where(['keyword' => $content])->find()) {
                #$str = json_encode($data, JSON_UNESCAPED_UNICODE);
                $moduleName = $data['module'];
                $rid        = $data['rid'];
                $this->moduleMsg($moduleName, $rid);
            }
        }

        // 当没有回复时交给默认消息处理
        $this->moduleMsg('message');

    }

    // 调用默认回复模块
    protected function moduleMsg($name, $rid = 0) {
        $name  = ucfirst($name);
        $class = 'Addons\\' . $name . '\SubProcessor';
        call_user_func_array([new $class, 'handler'], [$rid]);

    }


}